﻿using CoreShop.App.Scale;
using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.Model.UI;
using CoreShop.Services;
using FastMember;
using Loading;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using NPOI.POIFS.Properties;
using NPOI.SS.UserModel;
using NPOI.Util;
using Org.BouncyCastle.Asn1.Crmf;
using Org.BouncyCastle.Asn1.Ocsp;
using SqlSugar.Extensions;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Security.AccessControl;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using static CoreShop.Library.GlobalEnumVars;
using static System.Runtime.CompilerServices.RuntimeHelpers;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace CoreShop.App
{
    public partial class frmFoodInfo : UIForm
    {
        public bool returnValue;
        public corecmsfoodPost foodModel = new corecmsfoodPost();
        public long foodId = 0;
        public List<corecmsfoodunit> unitList = new List<corecmsfoodunit>();
        public int spuType = (int)GlobalEnumVars.GoodsSpuType.Standard;
        public corecmsfoodunit unitModel = null;
        public bool isNewCategory = false;
        private const string Pattern = @"^[a-zA-Z0-9_]*$";
        OpaqueCommand cmd = new OpaqueCommand();

        public class GetCodeModel
        {
            public string spuCode { get; set; }

            public string spuBarcode { get; set; }
        }

        public frmFoodInfo(long _foodId, long _foodTypeId,string _code,int _spuType = 1)
        {
            InitializeComponent();
            foodModel.foodTypeId = _foodTypeId;
            foodId = _foodId;
            this.spuCode.Text = _code;
            this.spuType = _spuType;
        }
        public frmFoodInfo()
        {
            InitializeComponent();
        }
        private void FrmEditInputs_Load(object sender, EventArgs e)
        {
            if (foodId > 0)
            {
                //string msg = "";
                //foodModel = new PosRemoteServices(AppConstVars.sUrl).GetEditFood(foodId, AppConstVars.sysUser.ccessToken, ref msg);
                //if (foodModel == null)
                //{
                //    UIMessageBox.Show("获取菜品异常", "系统出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                //    return;
                //}

                //if (foodModel.storeId != AppConstVars.sysStore.id)
                //{
                //    foreach (Control childControl in this.Controls)
                //    {
                //        childControl.Enabled = false;
                //    }

                //}

                //BindFoodSpec();
                //BindFoodPack();
                //LoadFoodType();
                //SetFoodTypeDisable();
            }
            else
            {
                foodModel.speclist = new List<corecmsfoodspecPost>();
                foodModel.detail = new corecmsfooddetailPost();                
            }
            //GetGoodCategroyList();
            LoadFoodCategroy();
            BindComboBoxData();
            ControlsDataBinding.DataBind(foodModel, this, DataSourceUpdateMode.OnPropertyChanged);
            try
            {
                if (foodModel.id <= 0)
                {

                }
                else
                {
                    saPrice.Text = foodModel.detail.minDiscount.ObjToString();
                }
            }
            catch { }

            if (spuType == (int)GlobalEnumVars.GoodsSpuType.VirtualGoods)
            {
                spuNumber.Text = "0000";
                spuCode.Text = "0000";
                spuName.Text = "临时商品";
                saPrice.ReadOnly = true;
                poPrice.ReadOnly = true;
                vipPrice.ReadOnly = true;
                vvipPrice.ReadOnly = true;
                commPrice.ReadOnly = true;
                this.Text = "新建临时商品";
            }
        }
    
        private void LoadFoodCategroy()
        {
            List<corecmsfoodcategory> lstSource = new corecmsfoodcategoryServices().AsQueryable()
                .Where(p => p.isDelete != true && p.tenantId == AppConstVars.sysStore.corpId).ToList();
            if (foodModel.foodTypeId != 0)
            {
                //是否有下级分类，下级分类才可以添加商品
                var foodTypeList = lstSource.Where(p => p.parentId == foodModel.foodTypeId).ToList();
                if (foodTypeList.Any()) foodModel.foodTypeId = 0;
            }                

            var selectNode = itemSortName.SelectedNode;
            if (selectNode != null)
            {
                foodModel.foodTypeId = CommFunc.ConvertToBigInt(selectNode.Tag);
            }
            itemSortName.Nodes.Clear();            
            var parents = lstSource.Where(p => p.parentId == 0).ToList();
            TreeNode treeNode1 = null;
            foreach (var item in parents)
            {
                treeNode1 = new TreeNode(item.name);
                treeNode1.Tag = item.id.ToString();
                itemSortName.Nodes.Add(treeNode1);
                if (foodModel.foodTypeId == item.id)
                {
                    itemSortName.SelectedNode = treeNode1;
                    SetGoodsStand(foodModel.foodTypeId);
                }

                var childs = lstSource.Where(p => p.parentId == item.id).ToList();
                foreach (var child in childs)
                {
                    TreeNode treeNode2 = new TreeNode(child.name);
                    treeNode2.Tag = child.id.ToString();
                    treeNode1.Nodes.Add(treeNode2);
                    if ((foodModel.foodTypeId == 0) || (foodModel.foodTypeId == child.id))
                    {
                        foodModel.foodTypeId = child.id;
                        itemSortName.SelectedNode = treeNode2;
                        SetGoodsStand(foodModel.foodTypeId);
                    }
                }
            }
            if (itemSortName.Nodes.Count > 0)
                itemSortName.Nodes[0].Expand();
            if ((foodModel.foodTypeId == 0) && (treeNode1 != null))
            {
                itemSortName.SelectedNode = treeNode1;
                SetGoodsStand(CommFunc.ConvertToBigInt(treeNode1.Tag));
            } 
            else 
                SetGoodsStand(foodModel.foodTypeId);
        }
                       
        private async void DoCreate()
        {           

            if (spuNumber.Text.IsNullOrEmpty()) spuNumber.Text = spuCode.Text;
            GsAddProductPdtInfoModel PostInfo = new GsAddProductPdtInfoModel();
            PostInfo.spuCode = spuNumber.Text;
            PostInfo.spuBarcode = spuCode.Text;
            PostInfo.spuName = spuName.Text;
            PostInfo.itemSortId = CommFunc.ConvertToBigInt(itemSortName.SelectedNode.Tag).ToString();
            PostInfo.itemSortName = itemSortName.Text;
            PostInfo.uomId = unitModel.uomId.ToString();
            PostInfo.uomName = unitModel.uomName;
            PostInfo.saPrice = CommFunc.ConvertToDecimal(saPrice.Text);
            PostInfo.vipPrice = CommFunc.ConvertToDecimal(vipPrice.Text);
            PostInfo.poPrice = CommFunc.ConvertToDecimal(poPrice.Text);
            PostInfo.vvipPrice = CommFunc.ConvertToDecimal(vvipPrice.Text);
            PostInfo.commPrice = CommFunc.ConvertToDecimal(commPrice.Text);
            PostInfo.specName = specName.Text;
            PostInfo.stand = foodModel.type;
            PostInfo.spuTypeId = spuType;
            var resultModel = await FoodApiUtil.SaveGoodsInfo(PostInfo);
            if (resultModel.status)
            {
                UIMessageTip.Show("新增成功！");
                DialogResult = DialogResult.OK;
            }
            else
            {
                MessageBox.Show(resultModel.msg);
            }
        }

        private void DoEdit()
        {
            //try
            //{
            //    string msg = "";
            //    corecmsfoodPost food = new PosRemoteServices(AppConstVars.sUrl).DoEditFood(foodModel, AppConstVars.sysUser.ccessToken);
            //    if (food != null)
            //    {
            //        if (new FoodUtil().SaveToFoodByConvert(food)) ShowSuccessTip("保存成功");
            //        this.Close();
            //    }
            //    else
            //    {
            //        UIMessageBox.Show("保存失败" + msg, "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
            //        return;
            //    }
            //}
            //catch (Exception)
            //{
            //    throw;
            //}
        }

        private void btnOk_ClickAsync(object sender, EventArgs e)
        {
            
        }

        private bool CheckData1()
        {          
            unitModel = null;
            string sNumber = spuNumber.Text;
            string ItemCode = spuCode.Text;
            string ItemName = spuName.Text;
            string UomName = uomName.Text;
            if (sNumber.Length > 15)
            {
                UIMessageTip.Show("商品编码过长！");
                return false;
            }
            if (ItemCode.Length > 15)
            {
                UIMessageTip.Show("商品条码过长！");
                return false;
            }
            if (string.IsNullOrEmpty(UomName))
            {
                UIMessageTip.Show("请选择单位！");
                return false;
            }
            unitModel = unitList.Find(p => p.uomName == uomName.Text.ToString());
            if (unitModel == null)
            {
                UIMessageTip.Show("输入的单位不存在！");
                return false;
            }
            if (string.IsNullOrEmpty(ItemCode))
            {
                UIMessageTip.Show("请输入商品代码！");
                spuCode.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(ItemName))
            {
                UIMessageTip.Show("请输入商品名称！");
                spuName.Focus();
                return false;
            }

            if (itemSortName.Text.IsNullOrEmpty())
            {
                UIMessageBox.Show("商品分类不能为空。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return false;
            }
            bool result = IsAlphanumericWithUnderscore(sNumber);
            if (!string.IsNullOrEmpty(sNumber))
            {                
                if (!result)
                {
                    UIMessageBox.Show("商品编码必须是包含数字、字母或下划线。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    spuName.Focus();
                    return false;
                }
            }
            result = IsAlphanumericWithUnderscore(ItemCode);
            if (!result)
            {
                UIMessageBox.Show("商品条码必须是包含数字、字母或下划线。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                spuCode.Focus();
                return false;
            }
            return true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSetReduceAmount_Click(object sender, EventArgs e)
        {

        }

        private void btnNormalFood_Click(object sender, EventArgs e)
        {
            btnStand.FillDisableColor = System.Drawing.Color.WhiteSmoke;
            btnWeigh.FillDisableColor = System.Drawing.Color.WhiteSmoke;
            btnCount.FillDisableColor = System.Drawing.Color.WhiteSmoke;
            btnStand.Selected = false;
            btnWeigh.Selected = false;
            btnCount.Selected = false;
            (sender as UIButton).Selected = true;
            (sender as UIButton).FillDisableColor = System.Drawing.Color.FromArgb(255, 189, 0);
            foodModel.type = CommFunc.ConvertToInt32((sender as UIButton).Tag);            
        }        

        public void BindComboBoxData()
        {
            #region 加载商品单位
            try
            {
                string msg = "";
                this.uomName.Items.Clear();
                //unitList = new FoodUtil().GetProductUnitList(AppConstVars.sysUser, ref msg);
                unitList = new corecmsfoodunitServices().AsQueryable().Where(p=>p.tenantId == AppConstVars.sysStore.corpId && p.delFlag == 0).ToList();
                this.uomName.DataSource = unitList;
                this.uomName.DisplayMember = "uomName";
                this.uomName.ValueMember = "uomId";
                if (unitList.Count > 0)
                {
                    this.uomName.SelectedIndex = 0;
                    var canDefaults = unitList.Where(p => p.canDefault == 0);
                    if (canDefaults.Any())
                    {
                        var canDefault = canDefaults.FirstOrDefault();
                        this.uomName.SelectedValue = canDefault.uomId;
                        this.uomName.Text = canDefault.uomName;
                    }
                    else
                    {
                        var unitItem = unitList.FirstOrDefault();
                        this.uomName.SelectedValue = unitItem.uomId;
                        this.uomName.Text = unitItem.uomName;
                    }
                }
            }
            catch (Exception ex) { }
            #endregion
        }

        private void saPrice_Enter(object sender, EventArgs e)
        {
            (sender as UITextBox).SelectAll();
        }

        private void SetGoodsStand(long foodTypeId)
        {            
            corecmsfoodcategory category = new corecmsfoodcategoryServices().GetById(foodTypeId);
            if (category != null)
            {
                switch (category.stand)
                {
                    case (int)GlobalEnumVars.stand.Count:
                        btnNormalFood_Click(btnCount, new EventArgs());
                        break;
                    case (int)GlobalEnumVars.stand.Weigh:
                        btnNormalFood_Click(btnWeigh, new EventArgs());
                        break;

                    default:
                        btnNormalFood_Click(btnStand, new EventArgs());
                        break;
                }
            }
        }

        private void itemSortName_NodeSelected(object sender, TreeNode node)
        {
            foodModel.foodTypeId = CommFunc.ConvertToBigInt(node.Tag);
            SetGoodsStand(foodModel.foodTypeId);
        }

        private async void btnGetCode_Click(object sender, EventArgs e)
        {
            cmd.ShowOpaqueLayer(pnl_Form, 125, true);
            try
            {
                //获取活动主信息
                var result = await FoodApiUtil.GetProductItemCode(AppConstVars.sysUser);
                if (result == null || string.IsNullOrEmpty(result.MessageOrString))
                {
                    return;
                }
                ApiReturnModel apiReturnModel = result.MessageOrString.JsonToEntity<ApiReturnModel>();
                if (apiReturnModel != null && apiReturnModel.data != null)
                {
                    //活动主信息不为空，实例化后再去获取子信息
                    GetCodeModel apiReturn = apiReturnModel.data.ToString().JsonToEntity<GetCodeModel>();
                    if (apiReturn != null)
                    {
                        this.spuNumber.Text = apiReturn.spuCode;
                        if (string.IsNullOrEmpty(this.spuCode.Text.Trim()))
                        {
                            this.spuCode.Text = apiReturn.spuBarcode;
                        }
                        spuName.Focus();
                        //spuName.SelectAll();
                    }
                }
                else
                {
                    UIMessageTip.ShowWarning("生成失败:" + apiReturnModel.msg);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                cmd.HideOpaqueLayer();
            }            
        }

        private void saPrice_Click(object sender, EventArgs e)
        {
            (sender as UITextBox).SelectAll();
        }

        private void frmFoodInfo_FormClosed(object sender, FormClosedEventArgs e)
        {
            HideWaitForm();
        }

        /// <summary>
        /// 检查输入的文本是否只包含数字、字母和下划线
        /// </summary>
        /// <param name="input">需要检查的文本</param>
        /// <returns>如果只包含允许的字符则返回true，否则返回false</returns>
        public static bool IsAlphanumericWithUnderscore(string input)
        {
            // 处理null情况
            if (input == null)
                return false;

            // 使用正则表达式进行匹配
            return Regex.IsMatch(input, Pattern);
        }
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (!CheckData1()) return;
            try
            {
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                foodModel.corpId = AppConstVars.sysUser.corpId;
                foodModel.storeId = AppConstVars.sysUser.storeId;
                foodModel.name = this.spuName.Text;
                foodModel.byName = this.specName.Text;
                foodModel.detail.departId = CommFunc.ConvertToBigInt(this.uomName.SelectedValue);
                foodModel.foodTypeId = CommFunc.ConvertToBigInt(itemSortName.SelectedNode.Tag);
                foodModel.detail.minDiscount = saPrice.Text.ObjToDecimal(0);
                foodModel.clientType = (int)GlobalEnumVars.ClientType.PosApp;//如果是前台提交，返回数据给前台
                if (foodModel.detail.isGoods != (int)GlobalEnumVars.FoodstockType.material)
                    foodModel.detail.quantity = 0;
                if (foodModel.id > 0)
                {
                    DoEdit();
                }
                else
                {
                    foodModel.modifyTime = 0;
                    DoCreate();
                }
                //SetControlClear();
            }
            catch (Exception)
            {
                throw;
            }
            finally { cmd.HideOpaqueLayer(); }
        }

        private async void spuCode_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(spuName.Text)) return;
            string strCode = spuCode.Text;
            if (string.IsNullOrEmpty(strCode) || strCode.Length < 13) return;
            try
            {
                GsAddProductPdtInfoModel PostInfo = new GsAddProductPdtInfoModel();
                PostInfo.spuBarcode = strCode;
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                var spuInfo = await FoodApiUtil.GetPdtStanderSpuInfo(PostInfo);
                if (spuInfo != null)
                {
                    this.spuName.Text = spuInfo.spuName;
                    this.saPrice.Text = spuInfo.saPrice.ToString();
                    this.poPrice.Text = spuInfo.poPrice.ToString();
                    var  sUnitModel = unitList.Find(p => p.uomName == spuInfo.uomName);
                    if (sUnitModel != null)
                    {
                        uomName.Text = sUnitModel.uomName;
                    }
                }
            }
            catch (Exception)
            {

            }
            finally { cmd.HideOpaqueLayer(); }
        }

        private void btnNewType_Click(object sender, EventArgs e)
        {
            frmFoodCategoryInfo frm = new frmFoodCategoryInfo(new corecmsfoodcategory());
            frm.Owner = this;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                isNewCategory = true;
                LoadFoodCategroy();
            }
            frm.Dispose();
        }
    }
}